#include "udp.h"
#include "queue.h"
#include "thread_pool.h"

void main(int argc, char **argv)
{
    int sockfd;
    struct sockaddr_in server; /* server's address information */
    struct sockaddr_in client; /* client's address information */
    socklen_t sin_size;
    int num;

    if (argc != 2)
    {                                 
        printf("Usage: %s, please input valid parameter!!!\n",argv[0]);
        exit(1);
    }
    printf("Welcome! this is a UDP server...\n ");

    /* Creating UDP socket */
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 
    {
            /* handle exception */
        perror("Creating socket failed.");
        exit(-1);
    }

    bzero(&server,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(atoi(argv[1]));
    server.sin_addr.s_addr = htonl (INADDR_ANY);
    if (bind(sockfd, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -1) 
    {
        /* handle exception */
        perror("Bind error.");
        exit(-1);
    } 

    /***** 初始化消息队列 ******/
    Elem *pelem;
    SQueue *queue;
    if(Queue_Init(queue) < 0) {
        printf("Init queue failed...\n");
        return;
    }

    sin_size = sizeof(struct sockaddr_in);
    char recvdata[DATA_MAXSIZE];
    char sendmsg[DATA_MAXSIZE];
    while (1) 
    {
        memset(recvdata, 0, DATA_MAXSIZE);
        memset(sendmsg, 0, DATA_MAXSIZE);

        num = recvfrom(sockfd, recvdata, DATA_MAXSIZE, 0, (struct sockaddr *)&client, &sin_size); 

        if (num < 0)
        {
            perror("recvfrom error\n");
            exit(1);
        }

        MSG recvmsg;
        memcpy(&recvmsg, recvdata, sizeof(recvmsg));

        printf("You got a message (%s) from %s\n", recvmsg.data, inet_ntoa(client.sin_addr));
        // printf("recvmsg:%ld\n", sizeof(recvmsg));
        // printf("recvdata:%ld\n", sizeof(recvdata));
        // printf("num:%d\n", num);

        /*****  入队 *****/
        memcpy(pelem ->data, &recvmsg, sizeof(recvmsg));
        memcpy(pelem ->client, &client, sizeof(client));
        if (Queue_Enqueue(queue, pelem) < 0){
            printf("insert queue failed...\n");
            return;
        }


        if(!strncmp(recvmsg.data, "quit", 4)) 
        {
           // char result[] = {"server quit..."};
           // sendto(sockfd, result, strlen(result), 0, (struct sockaddr *)&client, sin_size);
            break;
        }
        
        // sprintf(sendmsg, "send count:%d; time:%s; data:%s; data lengh:%d\n", recvmsg.id, recvmsg.time, recvmsg.data, recvmsg.lengh);
        // sendto(sockfd, sendmsg, strlen(sendmsg), 0, (struct sockaddr *)&client, sin_size);

    }

    close(sockfd);      /* close listenfd */ 
    return;
}